package com.weipai.demo.util;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.weipai.demo.enums.SMSCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 发送短信帮助类
 *
 * @author songmengqiang
 * @create 2018-08-30 14:49
 **/

public class SmsHelper {

    private static final Logger logger = LoggerFactory.getLogger(PropUtils.class);

    private static IAcsClient acsClient = null;

    static {
        try {
            initClient();
        } catch (ClientException e) {
            logger.error("init acsClient with error {}", e);
        }
    }

    /**
     * 发送六位验证码
     *
     * @param phone
     */
    public static String sendCheckCode(String phone) throws ClientException {
        Map<String, Object> params = new HashMap<>();
        String checkCode = randomString(6, true);//此处是生成6位数验证码  数字
        params.put("code", checkCode);
        sendMsg(phone, SMSCode.DEFAULT_CODE.getCode(), params);//默认通用验证吗  模板
        return checkCode;
    }

    /**
     * 发送短信
     *
     * @param phone
     * @param templateCode
     * @param params
     * @throws ClientException
     */
    public static void sendMsg(String phone, String templateCode, Map<String, Object> params) throws ClientException {
        //组装请求对象
        SendSmsRequest request = new SendSmsRequest();
        //使用post提交
        request.setMethod(MethodType.POST);
        //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
        request.setPhoneNumbers(phone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(PropUtils.getString("aliyun.message.signName"));
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(templateCode);
        //request.setTemplateParam("{\"code\":\"123\"}");//测试用,此处json一定要严格按照json格式书写
        String templateParam = JSON.toJSONString(params);
        request.setTemplateParam(templateParam);
        //可选-上行短信扩展码(扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");
        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
//        request.setOutId("yourOutId");
        //请求失败这里会抛ClientException异常
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

        if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
            //请求成功
            System.out.println(sendSmsResponse.getCode());
        } else {
            logger.info("send msg fail SendSmsResponse={}", sendSmsResponse);
            throw new RuntimeException("发送短信失败");
        }
    }


    /**
     * 获取IAcsClient对象
     *
     * @return
     * @throws ClientException
     */
    private static void initClient() throws ClientException {

        if (acsClient != null) {
            return;
        }
        logger.info("start init acsClient");
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        // 初始化ascClient需要的几个参数
        final String product = "Dysmsapi";// 短信API产品名称
        final String domain = "dysmsapi.aliyuncs.com";// 短信API产品域名
        // 秘钥key和secret
        final String ak = PropUtils.getString("aliyun.message.ak");
        final String sk = PropUtils.getString("aliyun.message.sk");
        // 初始化ascClient,暂时不支持多region
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", ak, sk);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        acsClient = new DefaultAcsClient(profile);
        logger.info("init ascClient success");
    }

    /**
     * 生成随机验证码
     *
     * @param length
     * @param isNumeric
     * @return
     */
    public static String randomString(int length, boolean isNumeric) {
        String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        if (isNumeric) {
            base = "0123456789";
        }
        Random random = new Random();
        StringBuffer buffer = new StringBuffer(length);
        for (int i = 0; i < length; i++) {
            buffer.append(base.charAt(random.nextInt(base.length())));
        }
        return buffer.toString();
    }
}
